//
//  AllContactsViewController.m
//  Assistant
//
//  Created by Hunk on 12-2-29.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AllContactsViewController.h"
#import "AddressBookManager.h"
#import "AddressBookPerson.h"
#import "PinYin.h"
#import <AddressBookUI/AddressBookUI.h>

@interface AllContactsViewController (Private)

- (AddressBookPerson *)personForGroupAtIndexPath:(NSIndexPath *)indexPath;

- (BOOL)searchResult:(NSString*)personName searchText:(NSString *)searchText;

- (NSString*)getFirstLetterOfPersonName:(NSString*)strPersonName;

@end

@implementation AllContactsViewController
@synthesize selectedMemberArray = _selectedMemberArray;
@synthesize delegate            = _delegate;

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    SAFE_RELEASE(_tableView)
    SAFE_RELEASE(searchDisplayController)
    SAFE_RELEASE(_searchDisplayArray)
    SAFE_RELEASE(_allContactsDictionary)
    SAFE_RELEASE(_sectionTitleArray)
    SAFE_RELEASE(_checkmarkDictionary)
    SAFE_RELEASE(_selectedMemberArray)
    SAFE_RELEASE(_delegate)
    SAFE_RELEASE(_originalMemberArray)
    
    [super dealloc];
}

- (id)init
{
    if((self = [super init]))
    {
        // Init variable
        _searchDisplayArray    = [[NSMutableArray alloc] init];
        _allContactsDictionary = [[NSMutableDictionary alloc] init];
        _sectionTitleArray     = [[NSMutableArray alloc] init];
        _checkmarkDictionary   = [[NSMutableDictionary alloc] init];
        _selectedMemberArray   = [[NSMutableArray alloc] init];
        _originalMemberArray   = [[NSMutableArray alloc] init];
    }
    return self;
}

#pragma mark - View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = NSLocalizedString(@"全部联系人", nil);
    
    self.navigationController.navigationBar.tintColor = TINT_COLOR;
    
    // BackgroundImageView
    UIImageView *backgroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 416.0)];
    [backgroundImageView setImage:[UIImage imageNamed:@"background.png"]];
    [self.view addSubview:backgroundImageView];
    [backgroundImageView release];
    
    // Cancel bar button
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"取消", nil)
                                                                          style:UIBarButtonItemStyleBordered
                                                                         target:self
                                                                         action:@selector(leftBarButtonHandle:)];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    [leftBarButtonItem release];
    
    // Sure bar button
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"确定", nil)
                                                                           style:UIBarButtonItemStyleBordered
                                                                          target:self
                                                                          action:@selector(rightBarButtonHandle:)];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    [rightBarButtonItem release];
    
    // Init tableView
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 416.0)
                                              style:UITableViewStylePlain];
    [_tableView setBackgroundColor:[UIColor clearColor]];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    // Search bar
    UISearchBar* searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    [searchBar setBarStyle:UIBarStyleDefault];
    [searchBar setDelegate:self];
    [searchBar setPlaceholder:NSLocalizedString(@"搜索", nil)];
    
    // SearchDisplayController
    searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar 
                                                                contentsController:self];
    [searchDisplayController setDelegate:self];
//    UITableView *tt =  searchDisplayController.searchResultsTableView;
//    UIView *view__ = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 44.0)];
//    [view__ setBackgroundColor:[UIColor redColor]];
//    tt.tableHeaderView = view__;
    [searchDisplayController setSearchResultsDelegate:self];
    [searchDisplayController setSearchResultsDataSource:self];
    
    // Set tableHeaderView
    _tableView.tableHeaderView = searchBar;
    [searchBar release];
    
    // Footer view
    UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 44.0)];
    [footerLabel setBackgroundColor:[UIColor clearColor]];
    [footerLabel setTextAlignment:UITextAlignmentCenter];
    [footerLabel setTextColor:[UIColor grayColor]];
    NSInteger nCount = [[AddressBookManager sharedManager] personCount];
    if(nCount <= 1)
    {
        [footerLabel setText:[NSString stringWithFormat:@"%d%@%@", nCount, @" ", NSLocalizedString(@"一位联系人", nil)]];
    }
    else
    {
        [footerLabel setText:[NSString stringWithFormat:@"%d%@%@", nCount, @" ", NSLocalizedString(@"位联系人", nil)]];
    }
    
    [_tableView setTableFooterView:footerLabel];
    [footerLabel release];
    
    // All contacts array
    NSArray *allContactsArray = [[AddressBookManager sharedManager] addressBookPersons];
    
    NSMutableDictionary* tempDic = [[NSMutableDictionary alloc] init];
    
    for(int i = 0; i < [allContactsArray count]; i++)
    {
        AddressBookPerson* addressBookPerson = [allContactsArray objectAtIndex:i];
        
        NSString* sectionTitle = [self getFirstLetterOfPersonName:[addressBookPerson personName]];
        
        if(nil != sectionTitle)
        {
            if([[tempDic allKeys] containsObject:sectionTitle])
            {
                NSMutableArray* tempArray = [[NSMutableArray alloc] init];
                
                [tempArray addObjectsFromArray:[tempDic objectForKey:sectionTitle]];
                
                [tempArray addObject:addressBookPerson];
                
                [tempDic setObject:tempArray forKey:sectionTitle];
                
                [tempArray release];
            }
            else
            {   
                [tempDic setObject:[NSArray arrayWithObjects:addressBookPerson, nil] 
                            forKey:sectionTitle];
            } 
        }
    }
    
    [_allContactsDictionary setDictionary:tempDic];
    
    [tempDic release];
    
    NSArray* titleArray = [[NSArray alloc] initWithArray:[[_allContactsDictionary allKeys] sortedArrayUsingSelector:@selector(compare:)]];
    [_sectionTitleArray setArray:titleArray];
    [titleArray release];
}

#pragma mark -
#pragma mark Set delegate
- (void)setDelegate:(id<AllContactsViewControllerDelegate>)delegate
{
    if(_delegate != delegate)
    {
        [_delegate release];
        
        _delegate = [delegate retain];
    }
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if(tableView == _tableView)
    {
        return [_sectionTitleArray count];
    }
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView == _tableView)
    {
        NSString *keyString = [_sectionTitleArray objectAtIndex:section];
        
        NSArray *memberArray = [_allContactsDictionary objectForKey:keyString];
        
        return [memberArray count];
    }
    return [_searchDisplayArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 46.0f;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if(tableView == _tableView)
    {
        return [_sectionTitleArray objectAtIndex:section];
    }
    
    return nil;
}

- (NSArray*)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if(tableView == _tableView)
    {
        if([_sectionTitleArray count] > 6)
        {
            NSMutableArray* sectionIndexTitlesArray = [NSMutableArray arrayWithObject:UITableViewIndexSearch];
            
            for(int i = 0; i < [_sectionTitleArray count]; i++)
            {
                [sectionIndexTitlesArray addObject:[_sectionTitleArray objectAtIndex:i]];
            }
            
            return sectionIndexTitlesArray;
        }
        return nil;
    }
    
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{   
	if (title == UITableViewIndexSearch) 
	{
		[tableView scrollRectToVisible:CGRectMake(0, 0, 320, 44) animated:YES];
        
		return -1;
	}
    
    return (index - 1);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView == _tableView)
    {
        static NSString *personCellIdentifier = @"person cell";
        
        PersonCell *cell = [tableView dequeueReusableCellWithIdentifier:personCellIdentifier];
        if(nil == cell)
        {
            cell = [[[PersonCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:personCellIdentifier] autorelease];
            
            [cell setDelegate:self];
        }
        
        AddressBookPerson *person = [self personForGroupAtIndexPath:indexPath];

        if([person selected] == YES)
        {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
        else
        {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        
        [cell setPerson:person];
        
        return cell;
    }
    else
    {
        static NSString *CellIdentifier = @"all contacts cell";
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
        if(cell == nil)
        {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                           reuseIdentifier:CellIdentifier] autorelease];
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        AddressBookPerson* addressBookPerson = [_searchDisplayArray objectAtIndex:indexPath.row];
        
        if([addressBookPerson selected] == YES)
        {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
        else
        {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        
        UIImage *personPhoto = [addressBookPerson personPhoto];
        if(nil != personPhoto)
        {
            cell.imageView.image = [addressBookPerson personPhoto];
        }
        else
        {
            cell.imageView.image = [UIImage imageNamed:@"icon_add.png"];
        }
        
        cell.textLabel.text = [addressBookPerson personName];
        
        return cell;
    }
    
    return nil;
    
    /*
    static NSString *CellIdentifier = @"all contacts cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:CellIdentifier] autorelease];
    }
    
    if(tableView == _tableView)
    {
        NSString *checkmarkKey = [NSString stringWithFormat:@"%d-%d", indexPath.section, indexPath.row];
        
        if([[_checkmarkDictionary allKeys] containsObject:checkmarkKey])
        {
            if([[_checkmarkDictionary objectForKey:checkmarkKey] boolValue])
            {
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
            }
            else
            {
                cell.accessoryType = UITableViewCellAccessoryNone;
            }
        }
        else
        {
            [_checkmarkDictionary setObject:@"NO" forKey:checkmarkKey];
        }
        
        cell.textLabel.text = [[self personForGroupAtIndexPath:indexPath] personName];
    }
    else
    {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        AddressBookPerson* addressBookPerson = [_searchDisplayArray objectAtIndex:indexPath.row];
        
        cell.textLabel.text = [addressBookPerson personName];
    }
    
    return cell;
     */
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if(_tableView == tableView)
    {   
        PersonCell* cell = (PersonCell *)[tableView cellForRowAtIndexPath:indexPath];
        
        // One person
        AddressBookPerson *addressBookPerson = [self personForGroupAtIndexPath:indexPath];
        
        if([addressBookPerson selected] == NO)
        {   
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
            
            [addressBookPerson setSelected:YES];
            
            // Add selected member to selectedMemberArray
            [_selectedMemberArray addObject:addressBookPerson];
        }
        else
        {   
            cell.accessoryType = UITableViewCellAccessoryNone;
            
            [addressBookPerson setSelected:NO];
            
            // Remove selected member from m_arraySelectedMember
            for(AddressBookPerson *person in _selectedMemberArray)
            {
                if([person recordID] == [addressBookPerson recordID])
                {
                    [_selectedMemberArray removeObject:addressBookPerson];
                    break;
                }
            }
        }
    }
    else
    {
        UITableViewCell* cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        
        // One person
        AddressBookPerson *addressBookPerson = [_searchDisplayArray objectAtIndex:indexPath.row];
        
        if([addressBookPerson selected] == NO)
        {   
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
            
            [addressBookPerson setSelected:YES];
            
            // Add selected member to selectedMemberArray
            [_selectedMemberArray addObject:addressBookPerson];
        }
        else
        {   
            cell.accessoryType = UITableViewCellAccessoryNone;
            
            [addressBookPerson setSelected:NO];
            
            // Remove selected member from m_arraySelectedMember
            for(AddressBookPerson *person in _selectedMemberArray)
            {
                if([person recordID] == [addressBookPerson recordID])
                {
                    [_selectedMemberArray removeObject:addressBookPerson];
                    break;
                }
            }
        }
    }
}

#pragma mark -
#pragma mark UISearchBar Delegate Methods
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{   
    [_searchDisplayArray removeAllObjects];
    
    NSArray* keyArray = [_allContactsDictionary allKeys];
    
    for(int i = 0; i < [keyArray count]; i++)
    {
        NSArray* contactsArray = [_allContactsDictionary objectForKey:[keyArray objectAtIndex:i]];
        
        for(int j = 0; j < [contactsArray count]; j++)
        {
            AddressBookPerson* addressBookPerson = [contactsArray objectAtIndex:j];
            
            NSRange range = [[addressBookPerson.personName lowercaseString] rangeOfString:[searchText lowercaseString]];
            
            if(0 != range.length)
            {
                [_searchDisplayArray addObject:addressBookPerson];
            }
        }
    }
}

- (void)searchDisplayController:(UISearchDisplayController *)controller didShowSearchResultsTableView:(UITableView *)tableView
{
    [_originalMemberArray setArray:_selectedMemberArray];
}

- (void)searchDisplayController:(UISearchDisplayController *)controller didHideSearchResultsTableView:(UITableView *)tableView
{
    if(![_originalMemberArray isEqualToArray:_selectedMemberArray])
    {
        [_tableView reloadData];
    }
}

#pragma mark -
#pragma mark Left BarButton Handle
- (void)leftBarButtonHandle:(id)sender
{
    [self dismissModalViewControllerAnimated:YES];//[self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -
#pragma mark Right BarButton Handle
- (void)rightBarButtonHandle:(id)sender
{
    if(_delegate && [_delegate respondsToSelector:@selector(didSelectedMembers:)])
    {
        for(AddressBookPerson *person in _selectedMemberArray)
        {
            [person setSelected:NO];
        }
        
        [_delegate didSelectedMembers:_selectedMemberArray];
    }
	
    [self dismissModalViewControllerAnimated:YES];
	//[self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -
#pragma mark PersonCell delegate method
- (void)personCell:(PersonCell *)cell didSelectedPerson:(AddressBookPerson *)person
{
    ABPersonViewController *abPersonViewController = [[ABPersonViewController alloc] init];
//    [abPersonViewController setAllowsEditing:YES];
//    [abPersonViewController setAllowsActions:YES];
    abPersonViewController.displayedPerson = [person record];
    [self.navigationController pushViewController:abPersonViewController animated:YES];
    [abPersonViewController release];
    
//    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:[person personName]
//                                                             delegate:nil
//                                                    cancelButtonTitle:@"OK"
//                                               destructiveButtonTitle:@"destructiveButtonTitle"
//                                                    otherButtonTitles:@"Other1", 
//                                  @"Other1", @"Other1", @"Other1", @"Other1", @"Other1", @"Other1", nil];
//    NSDictionary *phoneDic = [person personPhone];
//    NSArray *phoneKeysArray = [phoneDic allKeys];
//    for(int i = 0; i < [phoneKeysArray count]; i++)
//    {
//        [actionSheet addButtonWithTitle:[phoneDic objectForKey:[phoneKeysArray objectAtIndex:i]]];
//    }
//    [actionSheet showInView:self.view];
}

#pragma mark -
#pragma mark Private methods
#pragma mark -
#pragma mark personForGroupAtIndexPath
- (AddressBookPerson *)personForGroupAtIndexPath:(NSIndexPath *)indexPath;
{
    NSString* keyString = [_sectionTitleArray objectAtIndex:indexPath.section];
    
    NSArray* personArray = [_allContactsDictionary objectForKey:keyString];
    
    return [personArray objectAtIndex:indexPath.row];
}

#pragma mark -
#pragma mark searchResult:searchText:
- (BOOL)searchResult:(NSString*)personName searchText:(NSString *)searchText
{
	NSComparisonResult result = [personName compare:searchText options:NSCaseInsensitiveSearch range:NSMakeRange(0, searchText.length)];
	if(result == NSOrderedSame)
    {
		return YES;
    }
	
    return NO;
}

#pragma mark -
#pragma mark getFirstLetterOfPersonName
- (NSString*)getFirstLetterOfPersonName:(NSString*)strPersonName
{   
	if(0 != [strPersonName length])
	{
		if([self searchResult:strPersonName searchText:@"曾"])
			return @"Z";
		else if([self searchResult:strPersonName searchText:@"查"])
			return @"Z";
		else if([self searchResult:strPersonName searchText:@"仇"])
			return @"Q";
		else if([self searchResult:strPersonName searchText:@"朴"])
			return @"P";
		else if([self searchResult:strPersonName searchText:@"能"])
			return @"N";
		else if([self searchResult:strPersonName searchText:@"乐"])
			return @"Y";
		else if([self searchResult:strPersonName searchText:@"单"])
			return @"S";
		else if([self searchResult:strPersonName searchText:@"解"])
			return @"X";
		else if([self searchResult:strPersonName searchText:@"沈"])
			return @"S";
		else
		{
			unsigned short nChinese = [strPersonName characterAtIndex:0];
			
			return [[NSString stringWithFormat:@"%c", getPinYinFirstLetterFromChinese(nChinese)] uppercaseString];
		}	
	}
	
	return nil;
}

#pragma mark -
#pragma mark Others 
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
